package com.burst.reptile.modular.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.burst.reptile.common.constant.UserConstants;
import com.burst.reptile.common.exception.CustomException;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.framework.aspectj.lang.annotation.DataScope;
import com.burst.reptile.framework.web.entity.LayuiTreeSelect;
import com.burst.reptile.modular.system.entity.SysDept;
import com.burst.reptile.modular.system.mapper.SysDeptMapper;
import com.burst.reptile.modular.system.service.ISysDeptService;

import cn.hutool.core.util.StrUtil;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author wujin
 * @since 2020-05-22
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

	/**
	 * 查询部门管理数据
	 * 
	 * @param dept 部门信息
	 * @return 部门信息集合
	 */
	@Override
	@DataScope(deptAlias = "d")
	public List<SysDept> selectDeptList(SysDept dept) {
		return this.baseMapper.selectDeptList(dept);
	}

	@Override
	public List<SysDept> buildDeptTree(List<SysDept> depts) {
		List<SysDept> returnList = new ArrayList<SysDept>();
		List<Long> tempList = new ArrayList<Long>();
		for (SysDept dept : depts) {
			tempList.add(dept.getDeptId());
		}
		for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext();) {
			SysDept dept = (SysDept) iterator.next();
			// 如果是顶级节点, 遍历该父节点的所有子节点
			if (!tempList.contains(dept.getParentId())) {
				recursionFn(depts, dept);
				returnList.add(dept);
			}
		}
		if (returnList.isEmpty()) {
			returnList = depts;
		}
		return returnList;
	}

	@Override
	public List<LayuiTreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
		List<SysDept> deptTrees = buildDeptTree(depts);
		return deptTrees.stream().map(LayuiTreeSelect::new).collect(Collectors.toList());
	}

	/**
	 * 递归列表
	 */
	private void recursionFn(List<SysDept> list, SysDept t) {
		// 得到子节点列表
		List<SysDept> childList = getChildList(list, t);
		t.setChildren(childList);
		for (SysDept tChild : childList) {
			if (hasChild(list, tChild)) {
				// 判断是否有子节点
				Iterator<SysDept> it = childList.iterator();
				while (it.hasNext()) {
					SysDept n = (SysDept) it.next();
					recursionFn(list, n);
				}
			}
		}
	}

	/**
	 * 得到子节点列表
	 */
	private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
		List<SysDept> tlist = new ArrayList<SysDept>();
		Iterator<SysDept> it = list.iterator();
		while (it.hasNext()) {
			SysDept n = (SysDept) it.next();
			if (ToolUtil.isNotEmpty(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
				tlist.add(n);
			}
		}
		return tlist;
	}

	/**
	 * 判断是否有子节点
	 */
	private boolean hasChild(List<SysDept> list, SysDept t) {
		return getChildList(list, t).size() > 0 ? true : false;
	}

	@Override
	public int selectNormalChildrenDeptById(Long deptId) {
		return this.baseMapper.selectNormalChildrenDeptById(deptId);
	}

	@Override
	public String checkDeptNameUnique(SysDept dept) {
		Long deptId = ToolUtil.isEmpty(dept.getDeptId()) ? -1L : dept.getDeptId();
		SysDept info = this.baseMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
		if (ToolUtil.isNotEmpty(info) && info.getDeptId().longValue() != deptId.longValue()) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;

	}

	@Override
	public int insertDept(SysDept dept) {
		SysDept info = this.baseMapper.selectById(dept.getParentId());
		if (ToolUtil.isEmpty(info)) {
			throw new CustomException("上级部门不存在");
		}
		// 如果父节点不为正常状态,则不允许新增子节点
		if (StrUtil.equals(UserConstants.DEPT_DISABLE, info.getDeptStatus())) {
			throw new CustomException("部门停用，不允许新增");
		}
		dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
		return this.baseMapper.insert(dept);
	}

	@Override
	@Transactional
	public int updateDept(SysDept dept) {
		SysDept newParentDept = this.baseMapper.selectById(dept.getParentId());
		SysDept oldDept = this.baseMapper.selectById(dept.getDeptId());
		if (ToolUtil.isNotEmpty(newParentDept) && ToolUtil.isNotEmpty(oldDept)) {
			String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
			String oldAncestors = oldDept.getAncestors();
			dept.setAncestors(newAncestors);
			updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
		}
		int result = this.baseMapper.updateById(dept);
		if (UserConstants.DEPT_NORMAL.equals(dept.getDeptStatus())) {
			// 如果该部门是启用状态，则启用该部门的所有上级部门
			updateParentDeptStatus(dept);
		}
		return result;
	}

	@Override
	public int deleteDeptById(Long deptId) {
		return this.baseMapper.deleteDeptById(deptId);
	}

	@Override
	public boolean hasChildByDeptId(Long deptId) {
		int result = this.baseMapper.hasChildByDeptId(deptId);
        return result > 0 ? true : false;
	}

	@Override
	public boolean checkDeptExistUser(Long deptId) {
		int result = this.baseMapper.checkDeptExistUser(deptId);
        return result > 0 ? true : false;
	}

	/**
	 * 修改子元素关系
	 * 
	 * @param deptId       被修改的部门ID
	 * @param newAncestors 新的父ID集合
	 * @param oldAncestors 旧的父ID集合
	 */
	public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
		List<SysDept> children = this.baseMapper.selectChildrenDeptById(deptId);
		for (SysDept child : children) {
			child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
		}
		if (children.size() > 0) {
			this.baseMapper.updateDeptChildren(children);
		}
	}

	/**
	 * 修改该部门的父级部门状态
	 * 
	 * @param dept 当前部门
	 */
	private void updateParentDeptStatus(SysDept dept) {
		String updateUser = dept.getUpdateUser();
		dept = this.baseMapper.selectById(dept.getDeptId());
		dept.setUpdateUser(updateUser);
		this.baseMapper.updateDeptStatus(dept);
	}

	@Override
	public List<Long> selectDeptListByRoleId(Long roleId) {
		return this.baseMapper.selectDeptListByRoleId(roleId);
	}

}
